<template>
  <div class="audition143">
    <h3><strong>什么是函数柯里化</strong></h3>
    <p>柯里化是一种函数转换。会把<span class="color">f(a, b)</span>转换成<span class="color">f(a)(b)</span>的形式进行调用</p>
    <h3><strong>实现函数柯里化</strong></h3>
    <p>1. 箭头函数</p>
    <p>比如3个值相加的情况：</p>
    <code class="code">
      const add = x => y => z => x + y + z<br />
		  console.log(add(1)(2)(3)) // 6
    </code>
    <p>2. 改写toString或valueOf方法</p>
    <v-md-preview :text="text1" />
    <p>3. 柯里化得到add方法</p>
    <v-md-preview :text="text2" />
  </div>
</template>

<script>
const prefix = '``` js'
const suffix = '```'
export default {
  name: 'Audition143',
  data() {
    return {
      text1: `${prefix}
      function add() {
        var args = Array.from(arguments)
        var fn = function () {
          args.push(...arguments)
          return fn
        }
        fn.valueOf = function () {
          return args.reduce(function(a, b) {
            return a + b
          })
        }
        return fn
      }
      console.log(add(1)(2)(3).valueOf())
      \n${suffix}`,
      text2: `${prefix}
      function curry(fn) {
        let args = []
        return function sum(...args1) {
          if(args1.length) {
            args = [...args, ...args1]
            return sum
          }
          return fn.apply(null, args)
        }
      }
      function sum1(...args) {
        return args.reduce((a, b) => a+ b)
      }
      let add = curry(sum1)
      // 调用时，在最后要多加个()进行调用
      console.log(add(1)(2)(3, 4)())
      \n${suffix}`,
    }
  }
}
</script>

<style>

</style>